package com.ihunanren.biz.function.service.impl;

import java.util.List;
import java.util.Random;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;

import com.google.common.base.Throwables;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.ihunanren.biz.function.TextMather;
import com.ihunanren.biz.function.domain.Joke;
import com.ihunanren.biz.function.service.IWeixinService;
import com.ihunanren.common.CollectionUtils;
import com.ihunanren.dao.pojo.ReplyJokeDO;
import com.ihunanren.dao.weixin.IJokeDao;

/**
 * @author kalman03
 */
public class JokeService implements IWeixinService<Joke>{
	
	private final static String INTEGER_REGEX = "[1-9]\\d*";
	
	private final static int max_joke_show = 10;
	
	private final static int seed = 46903;
	
	@Autowired
	private IJokeDao jokeDao;
	
	@Override
	public List<Joke> getResponse(String input) {
		try {
			List<Joke> list = Lists.newArrayList();

			int count = getCount(input);

			List<ReplyJokeDO> replyJokeDOs = jokeDao.getJoke(getIds(count));
			if(CollectionUtils.isNotEmpty(replyJokeDOs)){
				for(ReplyJokeDO jokeDO : replyJokeDOs){
					Joke joke = new Joke();
					joke.setContent("    "+(jokeDO.getContent().replaceAll("\n", "").replaceAll("    ", "\n\t")));
					joke.setTitle(jokeDO.getTitle().trim());
					list.add(joke);
				}
				return list;
			}
		} catch (Exception e) {
			Throwables.propagate(e);
		}
		return null;
	}
	
	private Set<Integer> getIds(int count){
		Set<Integer> sets = Sets.newHashSet();
		while(sets.size() < count){
			sets.add(genarateNum());
		}
		return sets;
	}
	
	private int getCount(String input){
		int count = 1;
		Set<String> set   = TextMather.getMatherArray(input, INTEGER_REGEX);
		if(CollectionUtils.isNotEmpty(set)){
			for(String str : set){
				int num = Integer.parseInt(str);
				if(count < num && num != 0){
					count = num;
				}
			}
		}
		if(count > max_joke_show){
			count = max_joke_show;
		}
		return count;
	}
	
	
	private int genarateNum(){
		Random random = new Random();
		return random.nextInt(seed);
	}
}
